package org.ainlolcat.ctp.model.configuration.loader.impl;

import org.ainlolcat.ctp.guice.Loader;
import org.ainlolcat.ctp.model.configuration.Configuration;
import org.ainlolcat.ctp.model.configuration.loader.ConfigurationLoader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

/**
 * Created by IntelliJ IDEA.
 * User: ain
 * Date: 07.09.12
 * Time: 12:16
 * To change this template use File | Settings | File Templates.
 */
public class XMLConfigurationLoader implements ConfigurationLoader {
    public static String PARAM_FILENAME = "filename";
    private JAXBContext jc; 
    private Queue<String> files = new LinkedList<String>();
    private Configuration configuration;
    
    public Configuration load(Map<String, String> parameters) {
        String filename = parameters.get(PARAM_FILENAME);
        files.add(filename);
        configuration = Loader.get(Configuration.class);
        ensureJAXBContext();
        start();
        return configuration;
    }

    private void start(){
        while(!files.isEmpty()){
            String filename = files.poll();
        }
    }
    
    private void handleFile(String filename){
        
    }

    protected void ensureJAXBContext(){
        if (jc == null){
            try {
                jc = JAXBContext.newInstance(ConfigurationXML.class);
            } catch (JAXBException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }

    public ConfigurationXML unmarshal(String filename) throws Exception {
        ensureJAXBContext();
        Unmarshaller u = jc.createUnmarshaller();
        return (ConfigurationXML)u.unmarshal(new FileInputStream(filename));
    }

    public void marshal(ConfigurationXML config,String filename) throws Exception {
        ensureJAXBContext();
        Marshaller m = jc.createMarshaller();
        m.marshal(config, new FileOutputStream(filename));
    }

    @XmlRootElement
    public static class ConfigurationXML{
        public List<ModuleXML> modules;
    }

    public static class ModuleXML{
        public String clazz;
        public List<String> sources;
    }
}

